<?php

namespace app\api\service;

use app\common\model\Order;
use EasyWeChat\Factory;
use think\Exception;
use think\facade\Db;
use think\facade\Queue;

class OrderServer
{
    public static function create($response)
    {
        try {
            Db::startTrans();

            $time = time(); //创建时间

            $data = [
                'order_number' => self::create_order_number(),
                'pickup_time' => $response['pickup_time'],
                'pickup_address' => $response['pickup_address'],
                'estimated_weight' => $response['estimated_weight'],
                'contact_number' => $response['contact_number'],
                'cate_id' => '14',
                'recycle_type' => 1,
                'status' => 1,
                'images' => '',
                'remark' => $response['remark'],
                'user_id' => $response['user_id'],
                'order_status' => 0,
                'order_time' => $time,
                'create_time' => $time,
                'update_time' => $time,
            ];

            $orderId = Db::name('Order')->insertGetId($data);

            Db::commit();

            // 异步发送微信消息
            self::dispatchWechatMessageJob($data);

            return true;
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }


    /**
     * 分发微信消息任务到队列
     * @param array $orderData 订单数据
     */
    private static function dispatchWechatMessageJob(array $orderData)
    {
        // 确保配置正确后再调用队列
        try {
            Queue::push('app\job\SendWechatMessage', $orderData, 'wechat_message');
        } catch (\Exception $e) {
            // 如果队列配置有问题，可以选择记录日志或直接发送
            trace('队列发送失败: ' . $e->getMessage(), 'error');
            // 可选：直接调用发送方法
            // self::sendWechatMessageToMasters($orderData);
        }
    }

    /**
     * 给所有回收师傅发送微信消息
     * @param array $orderData 订单数据
     */
    public static function sendWechatMessageToMasters(array $orderData)
    {
        $user = Db::name('users')
            ->where(['id' => $orderData['user_id']])
            ->find();
        if (empty($user)) {
            return;
        }
        $orderData['nickname'] = $user['nickname'];

        // 获取所有回收师傅
        $masters = Db::name('users')
            ->where(['type_id' => 2, 'status' => 1])
            ->select();

        foreach ($masters as $master) {
            // 调用微信消息发送接口
            $openid = Db::name('users_auth')
                ->where(['user_id' => $master['id']])
                ->value('openid');
            self::sendWechatMessage($openid, $master, $orderData);
        }

    }

    private static function sendWechatMessage($openid, $master, $orderData)
    {

        $config = [
            'app_id' => "wxe474bb1488d38822",
            'secret' => "fe854cfe722195c8c4c9fec2a0d505a3",
            'response_type' => 'array',
            'log' => [
                'driver' => 'daily',
                'level' => 'debug',
                'file' => __DIR__ . '/../../../runtime/wechat.log',
            ],
        ];
        $app = Factory::miniProgram($config);

        // 构造模板消息内容
        $message = [
            'touser' => $openid, // 师傅的 openid
            'template_id' => '5postuF8dMqMst9eJwDxL4vWudhMP4H4G8f1XWFXvQw', // 需要替换为实际的模板 ID
            'page' => 'pages/other_order/order', // 点击跳转页面
            'data' => [
                'time5' => ['value' => date('Y-m-d H:i:s', $orderData['create_time'])], // 订单时间
                'name7' => ['value' => $orderData['nickname']], // 联系人姓名
                'phone_number12' => ['value' => $orderData['contact_number']], // 联系人电话
                'thing14' => ['value' => $orderData['pickup_address']], // 收货地址
                'time21' => ['value' => $orderData['pickup_time'] . ':00'], // 上门时间
            ]
        ];
        // 发送模板消息
        $result = $app->subscribe_message->send($message);

        // 记录发送结果
        if ($result['errcode'] !== 0) {
            trace('微信模板消息发送失败: ' . $result['errmsg'], 'error');
        }
    }


    /**
     * 更新信息
     * @param $response
     * @param $client
     * @param $user_id
     */
    public static function update($response, $user_id)
    {
        $time = time();
        try {
            $info = Order::find($response['id']);
            if ($info->isEmpty()) {
                throw new Exception('订单不存在');
            }

            Db::startTrans();
            $data = $response;
            $data['update_time'] = $time;
            Db::name('order')
                ->where(['user_id' => $user_id, 'id' => $response['id'], 'order_number' => $info['order_number']])
                ->update($data);

            Db::commit();

        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }

        return true;
    }

    public static function complete($response, $user_id)
    {
        $time = time();
        try {
            $info = Order::find($response['id']);
            if ($info->isEmpty()) {
                throw new Exception('订单不存在');
            }

            Db::startTrans();
            $data = $response;
            $data['pick_up_time'] = $time;
            $data['order_status'] = 2;
            $data['update_time'] = $time;
            $data['completion_time'] = $time;
            Db::name('order')
                ->where(['master_id' => $user_id, 'id' => $response['id'], 'order_number' => $info['order_number']])
                ->update($data);

            Db::commit();

        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }

        return true;
    }

    public static function delete($id, $user_id)
    {
        try {
            $info = Order::find($id);
            if ($info->isEmpty()) {
                throw new Exception('订单不存在');
            }
            Db::startTrans();
            Db::name('order')->where(['user_id' => $user_id, 'id' => $id])->delete();
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }

    public static function detail($id, $user_id)
    {
        try {
            $info = Order::findOrEmpty($id);
            if ($info->isEmpty()) {
                throw new Exception('订单不存在');
            }
            $master = Db::name('users')->where(['id' => $info['master_id']])->find();
            $info['master_phone'] = $master['mobile'];
            $info['master_name'] = $master['user_name'];
            return $info;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    private static function create_order_number(): string
    {
        return date('Ymd') . substr(
                implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))
                ), 0, 8);
    }

    public static function acceptOrder($params, $masterId)
    {

        try {
            $time = time();

            // 查找订单
            $order = Db::name('order')->where('id', $params['id'])->find();

            if (!$order) {
                throw new Exception('订单不存在');
            }

            // 检查订单状态是否为"等待上门"
            if ($order['order_status'] != 0) {
                throw new Exception('订单状态不正确，无法接单');
            }

            Db::startTrans();

            // 更新订单状态为"回收中"，并记录接单师傅
            $data = [
                'order_status' => 1, // 回收中
                'master_id' => $masterId, // 接单师傅ID
                'accept_time' => $time, // 接单时间
                'update_time' => $time
            ];

            Db::name('order')
                ->where(['id' => $params['id'], 'order_status' => 0])
                ->update($data);

            // 检查是否更新成功（防止并发接单）
            $updated = Db::name('order')->where(['id' => $params['id'], 'order_status' => 1])->find();
            if (!$updated) {
                throw new Exception('接单失败，订单可能已被其他师傅接取');
            }

            Db::commit();
            return true;

        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
    }

}